package com.mall.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.mall.entity.Coupon;
import com.mall.entity.UserCoupon;
import com.mall.mapper.UserCouponMapper;
import com.mall.service.IUserCouponService;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author sppxpp
 * @since 2023-04-16
 * 用户领取的优惠券表 服务实现类
 */
@Service
public class UserCouponServiceImpl implements IUserCouponService {
    final
    UserCouponMapper userCouponMapper;

    public UserCouponServiceImpl(UserCouponMapper userCouponMapper) {
        this.userCouponMapper = userCouponMapper;
    }

    /**
     * 删除优惠券
     * @param ids ids
     * @return success count
     */
    @Override
    public Integer deleteCoupon(List<Integer> ids) {
        if (ids.isEmpty()){
            return 0;
        }
        return userCouponMapper.update(null,new UpdateWrapper<UserCoupon>()
                .eq("coupon_id",ids.get(0))
                .set("is_delete",true));
    }

    /**
     * 领取优惠券
     * @param coupon entity
     * @return bool
     */
    @Override
    public Boolean claimCoupon(UserCoupon coupon) {
        return userCouponMapper.insert(coupon) > 0;
    }

    /**
     * 查询优惠券
     * @param flag 是否使用
     * @return list
     */
    @Override
    public List<Coupon> queryCoupon(Boolean flag, String userId) {
        return userCouponMapper.queryCoupon(flag,userId);
    }

    /**
     * 查询为过期优惠券数量
     *
     * @param userId
     * @return list
     */
    @Override
    public Integer queryCouponCount(String userId) {
        return userCouponMapper.queryCouponCount(userId);
    }

    /**
     * 查询优惠券
     * @param userId
     * @param couponId
     * @return list
     */
    @Override
    public UserCoupon queryCouponById(String userId, Integer couponId) {
        return userCouponMapper.selectOne(new QueryWrapper<UserCoupon>()
                .eq("is_delete",false)
                .eq("coupon_status",false)
                .eq("user_id",userId)
                .eq("coupon_id",couponId));
    }

    @Override
    public List<Coupon> queryExpiredCoupon(String userId) {
        return userCouponMapper.queryExpired(userId);
    }

    /**
     * 使用优惠券
     *
     * @param couponId
     * @param userId
     * @return bool
     */
    @Override
    public Boolean useCoupon(String couponId, String userId) {
        return userCouponMapper.update(null,new UpdateWrapper<UserCoupon>()
                .eq("user_id",userId)
                .eq("coupon_id",couponId)
                .set("coupon_status",true)) > 0;
    }
}
